const BookManager = {
    name: 'BookManager',
    components: {
        BookForm,
        BookTable,
        BookQueryForm
    },
    template: `
  <el-main>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>当前页面</el-breadcrumb-item>
    </el-breadcrumb>
    <BookQueryForm :categories="categories" @search="handleSearch"/>
    <div class="button-area">
    <el-button type="primary" @click="openForm(null)">
        <i class="fa-solid fa-plus"></i> 新增
    </el-button>
    <el-button type="danger">
        <i class="fa-solid fa-trash"></i> 删除
    </el-button>
    <el-button type="success">
        <i class="fa-solid fa-upload"></i> 上架
    </el-button>
    </div>

    <BookTable
            :pagination="pagination"
             @page-change="handlePageChange"  
             @size-change="handleSizeChange"  
            @edit="openForm"
            @delete="handleDelete"
    />
    <BookForm
            v-model:visible="showForm"
            :book-data="currentBook"
            :categories="categories"
            @submit="handleSubmit"
    />
</el-main>
    `,
    setup() {
        // 使用 Vue 的 reactive 创建响应式分页对象
        const pagination = Vue.reactive({
            currentPage: 1,
            pageSize: 10,
            total: 0,
            list: []
        });

        const categories = Vue.ref([]);
        const showForm = Vue.ref(false);
        const currentBook = Vue.ref(null);
        const queryParams = Vue.reactive({
            pageSize: 10,
            currentPage: 1
        });



        // 获取图书数据
        const fetchData = () => {
            axiosInstance.post(`/api/book/query`, queryParams)
                .then(response => {
                    // 更新分页数据
                    Object.assign(pagination, {
                        currentPage: response.data.currentPage,
                        pageSize: response.data.pageSize,
                        total: response.data.total,
                        list: response.data.list
                    });
                })
                .catch(error => {
                    console.error('获取图书数据失败:', error);
                });
        };

        // 提交表单时的处理函数
        const handleSubmit = (formData) => {
            const request = formData.bookId
                ? axiosInstance.put(`/api/book/`, formData)
                : axiosInstance.post(`/api/book/`, formData);

            request.then(response => {
                ElementPlus.ElMessage.success(formData.bookId ? '图书更新成功' : '图书添加成功');
                showForm.value = false;
                fetchData();
            })
                .catch(error => {
                    ElementPlus.ElMessage.error(error.message || '操作失败');
                    showForm.value = Boolean(formData.bookId);
                });
        };

        // 打开表单
        const openForm = (book) => {
            currentBook.value = book ? {...book} : null;
            if(categories.value.length === 0) {
                fetchCategory();
            }
            showForm.value = true;
        };

        // 删除图书
        const handleDelete = (id) => {
            ElementPlus.ElMessageBox.confirm('确定要删除该图书吗？', '确认删除', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                axiosInstance.delete(`${bookApi}/${id}`)
                    .then(() => {
                        ElementPlus.ElMessage.success('图书删除成功');
                        // 如果当前页只剩一条数据且不是第一页，则返回上一页
                        if(pagination.list.length === 1 && pagination.currentPage > 1) {
                            queryParams.currentPage -= 1;
                        }
                        fetchData();
                    })
                    .catch(error => {
                        ElementPlus.ElMessage.error(error.message || '删除失败');
                    });
            });
        };

        // 获取分类
        const fetchCategory = () => {
            axiosInstance.get('/api/bookCategory/listByStatus/1')
                .then(response => {
                    categories.value = response.data;
                })
                .catch(error => {
                    console.error('获取分类失败:', error);
                });
        };

        // 搜索处理
        const handleSearch = (params) => {
            // 重置分页参数
            queryParams.currentPage = 1;
            // 保留pageSize，清空其他参数
            const pageSize = queryParams.pageSize;
            Object.keys(queryParams).forEach(key => delete queryParams[key]);
            queryParams.pageSize = pageSize;
            queryParams.currentPage = 1;

            // 合并搜索参数
            Object.assign(queryParams, params);
            fetchData();
        };

        // 分页事件处理
        const handlePageChange = (page) => {
            queryParams.currentPage = page;
            fetchData();
        };

        const handleSizeChange = (size) => {
            queryParams.pageSize = size;
            queryParams.currentPage = 1; // 重置到第一页
            fetchData();
        };

        // 初始化
        Vue.onMounted(() => {
            fetchData();
            fetchCategory();
        });

        return {
            pagination,
            showForm,
            currentBook,
            categories,
            handlePageChange,
            handleSizeChange,
            handleSearch,
            openForm,
            handleDelete,
            handleSubmit
        };
    }
};